package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {
    //@Autowired
    private SysUserDao sysUserDao;
    //@Autowired
    private SysUserRoleDao sysUserRoleDao;

    public SysUserServiceImpl(SysUserDao sysUserDao, SysUserRoleDao sysUserRoleDao) {
        this.sysUserDao = sysUserDao;
        this.sysUserRoleDao = sysUserRoleDao;
    }

    @Override
    public List<SysUser> findUsers(SysUser sysUser) {
        return sysUserDao.selectUsers(sysUser);
    }

    @Override
    public SysUser findById(Integer id) {
        //基于id查询用户以及用户对应部门信息
        SysUser sysUser=sysUserDao.selectById(id);//user,dept
        if(sysUser==null)
            throw new ServiceException("用户已不存在");
        //基于id查询用户对应的角色id
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);//roles
        sysUser.setRoleIds(roleIds);
        return sysUser;
    }

    @Transactional
    @Override
    public int saveUser(SysUser sysUser) {
        //保存用户自身信息
        int rows=sysUserDao.insertUser(sysUser);
        //保存用户角色关系数据
        sysUserRoleDao.insertUserRoles(sysUser.getId(),
                sysUser.getRoleIds());
        return rows;
    }

    @Transactional
    @Override
    public int updateUser(SysUser sysUser) {
        //更新用户自身信息
        int rows=sysUserDao.updateUser(sysUser);
        if(rows==0)
            throw new ServiceException("用户可能已经不存在");
        //更新用户和角色关系数据
        sysUserRoleDao.deleteByUserId(sysUser.getId());
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }
    @Transactional
    @Override
    public int validById(Integer id, Integer valid) {
        String modifiedUser="admin";//后续是登录用户
        return sysUserDao.validById(id, valid, modifiedUser);
    }
}
